/**
 * Gerrit auto merge.
 */

;(function() {

  const chainData = {
    reply: {
      selector: 'button[title="Reply…"]',
      next: 'form',
    },
    form: {
      selector: [`input[type=radio][name=Code-Review]:last()`, `input[type=radio][name=Verified]:last()`],
      next: 'post',
    },
    post: {
      filter: {
        label: 'div',
        text: 'Post',
      },
      next: 'submit',
    },
    submit: {
      filter: [
        {
          label: 'div',
          text: 'Submit',
        },
      ],
    },
  }

  function main() {
    reply()
  }

  function reply() {
    const mergedMark = $('div:contains("Change has been successfully merged by"):last()')
    if (mergedMark.length != 0) {
      return
    }

    execClickChain('reply')
  }

  /**
   * Sync trigger dom click with chain data.
   */
  function execClickChain(chainName) {
    const data = chainData[chainName]

    let $doms
    let execTimes

    let intervalId = setInterval(resolveDom, 50)

    function resolveDom() {
      // Set to empty while it will be called recusive.
      $doms = []
      execTimes = 1

      setRefDoms($doms, data)

      if ($doms.length === 0 || execTimes > 200) {
        // Not has dom or excuted more than 10 seconds.
        console.warn(`[Gerrit Quick Merge Extension] The chain has no selector and filter, or maximum call times exceeded.`)
        clearInterval(intervalId)
        return
      }

      // The selector or filter must get unique dom.
      let isAllDomFound = $doms.every($dom => $dom.length === 1)
      if (isAllDomFound) {
        clearInterval(intervalId)
        exec()
      }
    }

    function exec() {
      $doms.forEach($dom => {
        $dom.click()
      })

      // Call next chain
      data.next && execClickChain(data.next)
    }
  }

  function setRefDoms($doms, data) {
    if (data.selector) {
      if (Array.isArray(data.selector)) {
        data.selector.forEach(item => {
          $doms.push($(item))
        })
      } else if (typeof data.selector === 'string') {
        $doms.push($(data.selector))
      }
    } else if (data.filter) {
      if (Array.isArray(data.filter)) {
        data.filter.forEach(item => {
          $doms.push(getDomByFilter(item))
        })
      } else if (typeof data.filter === 'object') {
        $doms.push(getDomByFilter(data.filter))
      }
    }
  }

  function getDomByFilter(data) {
    return $(data.label).filter(function() {
      return $(this).text() === data.text
    })
  }

  main()
})()
